package com.example.demo.service.impl;

import com.example.demo.service.PrintService;
import com.example.demo.util.FileUtil;
import com.example.demo.util.JsonUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 打印Service实现类
 *
 * @author nrz
 * @date 2024/8/31
 */
@Service
public class PrintServiceImpl implements PrintService {

    @Value(value = "${print.data.root}")
    private String printDataRoot;

    private static String projectPath = FileUtil.projectPath;

    private static String sepa = FileUtil.getSystemSeparator();

    @Override
    public Map<String, Object> savePrintData(String projectName, String printName, Map<String, Object> printData) throws Exception {
        Map<String, Object> result = new HashMap<>();
        result.put("projectName", projectName);
        result.put("printName", printName);
        String jsonPath = printDataRoot + sepa + projectName + sepa + printName + ".json";
        JsonUtil.writeToJsonFile(jsonPath, printData);
        return result;
    }

    @Override
    public Map<String, Object> getPrintConfigAndData(String projectName, String configName, String printName) {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> printConfig = getPrintConfig(projectName, configName);
        Map<String, Object> printData = getPrintData(projectName, printName);
        result.put("printConfig", printConfig);
        result.put("printData", printData);
        return result;
    }

    /**
     * 获取打印模板
     * @param projectName 项目名称
     * @param configName 打印模板标识
     * @return 打印模板
     */
    public Map<String, Object> getPrintConfig(String projectName, String configName) {
        try {
            String configFilePath  = projectPath + sepa + "print_config" + sepa + projectName + sepa
                                     + configName + sepa + "print.json";
            String jsonStr = JsonUtil.readFromFile(configFilePath);
            return JsonUtil.parseObject(jsonStr, Map.class);
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 获取打印数据
     * @param projectName 项目名称
     * @param printName 打印数据标识
     * @return 打印数据
     */
    public Map<String, Object> getPrintData(String projectName, String printName) {
        try {
            String dataFilePath  = printDataRoot + sepa + projectName + sepa + printName + ".json";
            String jsonStr = JsonUtil.readFromFile(dataFilePath);
            return JsonUtil.parseObject(jsonStr, Map.class);
        } catch (Exception e) {
            throw e;
        }

    }

}
